﻿using CKS.PLC.Core.Core;
using Cronos;
using Infrastructure;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.Model.Models._2409;

namespace CKS.PLC.Core.Alarm
{
    /// <summary>
    /// 设备状态存储OEE
    /// </summary>
    public class OP150_HC_DeviceStatus_Action
    {
        internal void Proccess(McClient mcClient, short runState, short deviceMode)
        {
            var fsql = InternalApp.Fsql;
            var _expression = CronExpression.Parse("0/1 * * * * ?", CronFormat.IncludeSeconds);

            var next = _expression.GetNextOccurrence(mcClient.LastProccessDeviceStatusTime, TimeZoneInfo.Local);
            var delay = next.Value - DateTimeOffset.Now;
            if (delay.TotalMilliseconds < 990 && delay.TotalMilliseconds > 0)
            {
                return; //两次间隔不到1秒
            }
            mcClient.LastProccessDeviceStatusTime = DateTimeOffset.Now;
            // EventBus.AddLog($"OEE测试信息 {DateTime.Now.ToString("HH:mm:ss")}");

            //读取状态信息存储到数据库
            /*
                运行状态：1=空闲，2=运行中，3=故障；4=待料中；
                设备模式：1=空模式；2=手动；4=初始化；8=自动；16=自动模式下暂停;
             */
            var log = new DeviceStatusLog()
            {
                DeviceCode = mcClient.PlcInfo.WorkstationCode,
                PlcId = mcClient.PlcInfo.Id,
                RunState = runState,
                DeviceMode = deviceMode,
                IsRunning = runState == 2 ? 1 : 0
            };
            fsql.Insert(log).ExecuteAffrows();
            fsql.Delete<DeviceStatusLog>().Where(a=>a.CreatedTime < DateTime.Now.AddDays(-7) ).ExecuteAffrows();
        }
    }
}
